package ma.xin.shi;

import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;

/**
 * 可添加项的 Combo 组件封装
 */
public class AddableCombo extends Composite {

    private Combo combo;

    public AddableCombo(Composite parent, int style, String labelText) {
        super(parent, SWT.NONE);
        createContents(labelText);
    }

    private void createContents(String labelText) {
        this.setLayout(new GridLayout(2, false));
        this.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

        // Label
        Label label = new Label(this, SWT.NONE);
        label.setText(labelText);

        // 占位用的空 Label
        new Label(this, SWT.NONE);

        // Combo
        combo = new Combo(this, SWT.DROP_DOWN | SWT.BORDER);
        combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

        // Add Button (+)
        Button addButton = new Button(this, SWT.PUSH);
        addButton.setText("+");
        addButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));

        // 按钮事件：弹出输入框并添加项
        addButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                InputDialog dialog = new InputDialog(getShell(), "添加新项", "请输入要添加的内容：", "", null);
                if (dialog.open() == Window.OK) {
                    String newItem = dialog.getValue();
                    if (newItem != null && !newItem.trim().isEmpty()) {
                        combo.add(newItem.trim());
                        combo.select(combo.getItemCount() - 1); // 选择新添加项
                    }
                }
            }
        });
    }

    /**
     * 获取当前 Combo 中的所有项
     */
    public String[] getItems() {
        return combo.getItems();
    }

    /**
     * 获取当前选中的项
     */
    public String getSelection() {
        return combo.getText();
    }

    /**
     * 设置 Combo 的初始内容
     */
    public void setItems(String[] items) {
        combo.setItems(items);
        if (items.length > 0) {
            combo.select(0);
        }
    }
}
